<!-- @format -->

<template>
	<div class="ma-content-block lg:flex justify-between p-4">
		<!-- CRUD 组件 -->
		<ma-crud @selection-change="setSelectedKeys" :options="options" :columns="columns" ref="crudRef">
			<template #dept_id="{ record }">
				<!-- 对标题加上 tag -->
				<a-tag color="blue">{{ record?.dept?.name }}</a-tag>
			</template>
			<template #car_no="{ record }">
				<!-- 对标题加上 tag -->
				<a-tag color="blue" v-for="(item, index) in record.detail">{{
					item.prediction.car_no + ','
				}}</a-tag>
			</template>
			<template #operationBeforeExtend="{ record }">
				<a-link @click="printer(record)">打印 </a-link>
				<a-link @click="watehouseRecord(record)">仓储明细</a-link>
			</template>
			<template #tableBeforeButtons>
            <a-button @click="setFdsl(record)" type="outline">仓储下单</a-button>
          </template> 
		</ma-crud>
		<a-modal :mask-closable="false"  :footer="false" :width="1000" v-model:visible="visibleRecord">
			<template #title> 仓储明细 </template>
			<WarehouseOrderrecord ref="warehouseRecordRef" />
		</a-modal>

    <a-modal :mask-closable="false" 
		width="auto"
		:top="40"
		v-model:visible="show"
		:alignCenter="false"
		:body-style="{
			padding: 0,
		}"
	>
		<template #title> 打印 </template>

		<div class="view-content">
			<div class="form">
				<div class="form-item">
					<lable>作业地点： </lable>
					<a-input @input="changeAds"></a-input>
				</div>
				<div class="form-item">
					<lable>作业项目： </lable>
					<a-input @input="changeItem"></a-input>
				</div>
				<div class="form-item">
					<lable>备注： </lable
					><a-input v-model="remarks" @input="editRemarks"></a-input>
				</div>
			</div>

			<prientTable
				:columns="p_columns"
				:data="p_data"
				title="汽车作业派工单"
				v-if="show"
			></prientTable>
		</div>

		<template #footer>
			<a-button v-print="printObj" type="primary">打印</a-button>
		</template>
	</a-modal>

	    <!-- 分单受理弹窗 -->
	<a-modal :mask-closable="false"  v-model:visible="fdslvisible" :width="900" title="仓储提货" @cancel="handlefdslCancel" :ok-loading="okloading"
      @ok="handlefdslBeforeOk">
      <div style="margin-bottom:5px;">
        <a-tag color="blue" size="large">当前共选择 <span style="color:red;margin:0px 10px;">{{ nums }} </span> 条预报信息</a-tag>
      </div>
      <div style="display:flex;margin-bottom:2%">
        <div style="display:flex;align-items: center;flex:1">
          <div>是否对装 ： </div>
          <a-select v-model="buff_typeid" :style="{'width':'210px'}"  placeholder="请选择">
            <a-option :disabled="item.key != 2" v-for="item of buff_type" :value="item.key" :label="item.title" />
          </a-select>
        </div>
        <div style="display:flex;align-items: center;flex:1">
          <div>配送方式 ： </div>
          <a-select v-model="pick_typeid" :style="{'width':'210px'}" placeholder="请选择">
            <a-option :disabled="item.key != 4 && item.key != 3" v-for="item of pick_type" :value="item.key" :label="item.title" />
          </a-select>
        </div>
        <div style="display:flex;align-items: center;flex:1">
          <div>选择地址 ： </div>
          <a-select v-model="address_id" :style="{'width':'210px'}" placeholder="请选择" @change="addressChange">
            <a-option v-for="item of addresslist" :value="item.id" :label="item.address" />
          </a-select>
        </div>
      </div>
      <div style="display:flex;align-items: center;justify-content: space-between;margin-bottom:2%">
        <div style="display:flex;align-items: center;">
          <span>收货手机 ： </span>
          <input disabled="true" v-model="addobj.delivery_mobile" type="text" class="input" style="width:120px" />
        </div>
        <div style="display:flex;align-items: center;">
          <span>收货地址 ： </span>
          <input disabled="true" v-model="addobj.delivery_address" type="text" class="input" style="width:120px" />
        </div>
        <div style="display:flex;align-items: center;">
          <span>收货电话 ： </span>
          <input disabled="true" v-model="addobj.delivery_tel" type="text" class="input" style="width:120px" />
        </div>
        <div style="display:flex;align-items: center;">
          <span>收货单位 ： </span>
          <input disabled="true" v-model="addobj.delivery_unit" type="text" class="input" style="width:140px" />
        </div>
      </div>
      <div style="display:flex;margin-bottom:2%">
        <div style="display:flex;align-items: center;flex:1">
          <div>选择车辆 ： </div>
          <div style="flex:1">
            <a-select v-model="drivers_id"   placeholder="请选择" multiple>
              <a-option v-for="item of drivers.value" :value="item?.id" :label="item?.default_car?.car_no" />
            </a-select>
          </div>
          
        </div>
      </div>

      <a-table :pagination="false" :bordered="{ wrapper: true, cell: true }" :columns="columnss" :data="datas">
        <template #receiver="{ rowIndex }">
          <input v-model="datas[rowIndex].receiver" type="text" class="input" />
        </template>
        <template #receiver_mobile="{ rowIndex }">
          <input v-model="datas[rowIndex].receiver_mobile" type="text" class="input" />
        </template>
        <template #area="{ rowIndex }">
          <input v-model="datas[rowIndex].area" type="text" class="input" />
        </template>
        <template #address="{ rowIndex }">
          <input v-model="datas[rowIndex].address" type="text" class="input" />
        </template>
        <template #number="{ rowIndex }">
          <input v-model="datas[rowIndex].number" type="text" class="input" />
          <p><a-tag style="margin-top:5px;" color="blue">剩余件数：{{ datas[rowIndex].number }}</a-tag></p>
        </template>
        <template #weight="{ rowIndex }">
          <input v-model="datas[rowIndex].weight" type="text" class="input" />
          <p><a-tag style="margin-top:5px;" color="blue">剩余吨数：{{ datas[rowIndex].weight }}</a-tag></p>
        </template>
      </a-table>

    </a-modal>

	</div>
</template>
<script setup>
	import { ref, reactive } from "vue";
	import warehouseOrder from "@/api/warehouse/warehouseOrder";
	import { Message } from "@arco-design/web-vue";
	import commonApi from '@/api/common';
	import predictionAddress from '@/api/prediction/predictionAddress'
	import tool from "@/utils/tool";
	import predictionOrderDetail from '@/api/prediction/predictionOrderDetail'
	import WarehouseOrderrecord from "@/views/warehouse/orderRecord/index.vue";
	import * as common from "@/utils/common";
	import predictionOrder from '@/api/prediction/predictionOrder'
	import prientTable from "@/components/prientTable/index.vue";
	import { request } from "@/utils/request.js";

	const crudRef = ref();
	const warehouseRecordRef = ref();
	const visibleRecord = ref(false);
	let ids = [];
	let keys = [];
	let datas = [];
	let pick_type = [];
	let buff_type = [];
	let addresslist = [];
	const pick_typeid = ref();
	const address_id = ref();
	const buff_typeid = ref();
	let ccArr = [];
	let okloading = false;
	const loadings = ref(true);
	const ccid = ref(0);
	const nums = ref(0)
	const hengArr = ref([]);
	const zongArr = ref([]);
	const cengArr = ref([]);
	const addobj = reactive({
	lat: '',
	lng: '',
	delivery_mobile: '',
	delivery_address: '',
	delivery_tel: '',
	delivery_unit: ''
	})
	const pick_method = ref()
	const drivers_id = ref()
	const drivers = reactive([]);
	const fdslvisible = ref(false)
	let columnss = [
    {
      title: '原票号',
      dataIndex: 'prediction.ticket_number',
    },
    {
      title: '车号',
      dataIndex: 'prediction.car_no',
    }, {
      title: '发站',
      dataIndex: 'prediction.producer',
    }, {
      title: '品名',
      dataIndex: 'prediction.goods_name',
    }, {
      title: '数量(件)',
      dataIndex: 'prediction.number',
      slotName: 'number'
    }, {
      title: '重量(吨)',
      dataIndex: 'prediction.weight',
      slotName: 'weight'
    }
  ]


  const handlefdslBeforeOk = async (e) => {
    if (addobj.delivery_mobile == '') {
      return Message.error('收货手机不能为空')
    }
    if (addobj.delivery_address == '') {
      return Message.error('收货地址不能为空')
    }
    if (addobj.delivery_unit == '') {
      return Message.error('收货单位不能为空')
    }
    if (addobj.lat == '') {
      return Message.error('纬度不能为空')
    }
    if (addobj.lng == '') {
      return Message.error('经度不能为空')
    }
    if (addobj.address_id == '') {
      return Message.error('请选择地址')
    }
    datas.map((v,i)=>{
		v.pick_number = v.number
		v.pick_weight = v.weight
	})
    let options = {
      item: datas,
      leixing: {
        butt: buff_typeid,
        pick: pick_typeid
      },
      car_ids:drivers_id.value.join(','),
      delivery_mobile: addobj.delivery_mobile,
      delivery_address: addobj.delivery_address,
      delivery_tel: addobj.delivery_tel,
      delivery_unit: addobj.delivery_unit,
      lat: addobj.lat,
      lng: addobj.lng,
    }
    let cc = await predictionOrder.save(options)
    if (cc.success) {
      return Message.success('分理成功！')
      crudRef.value.refresh()
      crudRefJzx.value.refresh()
    } else {
      return Message.error('分理失败！')
      crudRef.value.refresh()
      crudRefJzx.value.refresh()
    }
    fdslvisible.value = false;
    okloading = false
  }



	const setSelectedKeys = (val) => {
		keys = val
	}

	//仓储明细
	const watehouseRecord = (currentRow) => {
		warehouseRecordRef.value.open(currentRow);
		visibleRecord.value = true;
	};
	
	const handlefdslCancel = () => {
		fdslvisible.value = false;
	}

	const numberOperation = (newValue, id, numberName) => {
		warehouseOrder
			.numberOperation({ id, numberName, numberValue: newValue })
			.then((res) => {
				res.success && Message.success(res.message);
			})
			.catch((e) => {
				console.log(e);
			});
	};

	const switchStatus = (statusValue, id, statusName) => {
		warehouseOrder
			.changeStatus({ id, statusName, statusValue })
			.then((res) => {
				res.success && Message.success(res.message);
			})
			.catch((e) => {
				console.log(e);
			});
	};

	const options = reactive({
		id: "flyos_warehouse_order",
		rowSelection: {
			showCheckedAll: true,
		},
		pk: "id",
		operationColumn: true,
		operationWidth: 160,
		isDbClickEdit:false,
		bordered: { cell: true },
		formOption: {
			viewType: "modal",
			width: 600,
		},
		api: warehouseOrder.getList,
		recycleApi: warehouseOrder.getRecycleList,
		add: {
			show: true,
			api: warehouseOrder.save,
			auth: ["warehouse:order:save"],
		},
		edit: {
			show: true,
			api: warehouseOrder.update,
			auth: ["warehouse:order:update"],
		},
		delete: {
			show: true,
			api: warehouseOrder.deletes,
			auth: ["warehouse:order:delete"],
			realApi: warehouseOrder.realDeletes,
			realAuth: ["warehouse:order:realDeletes"],
		},
		recovery: {
			show: true,
			api: warehouseOrder.recoverys,
			auth: ["warehouse:order:recovery"],
		},
		import: {
			show: true,
			url: "warehouse/order/import",
			templateUrl: "warehouse/order/downloadTemplate",
			auth: ["warehouse:order:import"],
		},
		export: {
			show: true,
			url: "warehouse/order/export",
			auth: ["warehouse:order:export"],
		},
	});

	const columns = reactive([
		{
			title: "ID",
			dataIndex: "id",
			formType: "input",
			addDisplay: false,
			editDisplay: false,
			hide: true,
			commonRules: {
				required: true,
				message: "请输入ID",
			},
		},
		{
			title: "订单号",
			dataIndex: "order_no",
			formType: "input",
			align: "center",
			search: true,
			commonRules: {
				required: true,
				message: "请输入订单号",
			},
		},
		{
			title: "客户姓名",
			dataIndex: "dept_id",
			align: "center",
			formType: "select",
			dict: {
				// 远程通用接口请求，新版代码生成都有一个 remote 接口
				remote: "system/dept/remote",
				// 指定组件接收的props
				props: { label: "name", value: "id" },
				// 开启分页
				openPage: true,
				// 远程请求配置项
				remoteOption: {
					// 按用户名排序
					sort: { id: "desc" }, // 如果不指定排序方式，默认为正序排序
					// 设置查询的字段
					select: ["id", "name"],
					// 设置数据过滤
					filter: {
						type:['=',2],
						status: ['=',1]
					},
					// 关联模型
					relations: [],
				},
			},
		},
		{
			title: "车号",
			dataIndex: "car_no",
			align: "center",
			formType: "input-number",
			search: false,
		},
		{
			title: "库存件数",
			dataIndex: "zong_number",
			align: "center",
			formType: "input-number",
			search: true,
			min: 0,
			max: 999999,
			step: 1,
		},
		{
			title: "库存吨数",
			dataIndex: "zong_weight",
			align: "center",
			formType: "input-number",
			search: true,
			min: 0,
			max: 999999,
			step: 0.01,
			precision: 2,
		},
		{
			title: "剩余件数",
			dataIndex: "yu_number",
			formType: "input-number",
			align: "center",
			search: true,
			min: 0,
			max: 999999,
			step: 1,
		},
		{
			title: "剩余吨数",
			dataIndex: "yu_weight",
			align: "center",
			formType: "input-number",
			search: true,
			min: 0,
			max: 999999,
			step: 0.01,
			precision: 2,
		},
		{
			title: "状态",
			dataIndex: "status",
			align: "center",
			formType: "select",
			search: true,
			// commonRules: {
			//     required: true,
			//     message: "请输入状态"
			// },
			dict: {
				data: [
					{
						label: "待装卸",
						value: "1",
					},
					{
						label: "仓储中",
						value: "2",
					},
					{
						label: "已完成",
						value: "3",
					},
				],
				translation: true,
				tagColors: { 1: "gray", 2: "blue", 3: "green" },
			},
		},
		{
			title: "创建时间",
			dataIndex: "created_at",
			formType: "range",
			align: "center",
			search: true,
			addDisplay: false,
			editDisplay: false,
			showTime: true,
		},
		{
			title: "更新时间",
			dataIndex: "updated_at",
			formType: "date",
			addDisplay: false,
			editDisplay: false,
			hide: true,
			showTime: true,
		},
		{
			title: "删除时间",
			dataIndex: "deleted_at",
			formType: "date",
			addDisplay: false,
			editDisplay: false,
			hide: true,
			showTime: true,
		},
		{
			title: "更新者",
			dataIndex: "updated_by",
			formType: "input",
			addDisplay: false,
			editDisplay: false,
			hide: true,
		},
		{
			title: "创建者",
			dataIndex: "created_by",
			formType: "input",
			addDisplay: false,
			editDisplay: false,
			hide: true,
		},
	]);

	const printObj = {
		id: "prient-content",
		popTitle: "页面打印",
		openCallback: (vue) => {
			request({
				url: "warehouse/order/loadAdd",
				method: "post",
				data: {
					order_id: printID.value,
				},
			});
		},
	};

	const printID = ref("");

	// 是否显示打印弹窗
	const show = ref(false);
	// 点击打印
	function printer(e) {
		printID.value = e.id;
		request({
			url: "warehouse/orderRecord/index",
			method: "get",
			params: {
				warehouse_order_id: e.id,
			},
		}).then((res) => {
			p_data.value = res.data.items.map((item) => ({
				...item,
				user_name: e.dept.name,
			}));
			show.value = true;
		});
	}

	// 表单所需要的字段
	const remarks = ref("");

	const p_columns = reactive([
		{
			title: "作业地点",
			dataIndex: "w_address",
			formType: "input",
			placeholder: "请输入作业地点",
		},
		{
			title: "作业项目",
			dataIndex: "w_item",
			formType: "input",
			placeholder: "请输入作业项目",
		},
		{
			title: "车号",
			dataIndex: "prediction.car_no",
		},
		{
			title: "品名",
			dataIndex: "prediction.goods_name",
		},
		{
			title: "件数",
			dataIndex: "pick_number",
		},
		{
			title: "货主单位",
			dataIndex: "user_name",
		},
		{
			title: "备注",
			dataIndex: "remarks",
		},
	]);

	const p_data = ref([]);

	function editRemarks(e) {
		p_data.value.forEach((item) => {
			item.remarks = e;
		});
	}

	function changeAds(e) {
		p_data.value.forEach((item) => {
			item.w_address = e;
		});
	}

	function changeItem(e) {
		p_data.value.forEach((item) => {
			item.w_item = e;
		});
	}

	//仓储下单
	// 分单受理
	const setFdsl = (row) => {
	  nums.value = keys.length
	  warehouseOrder.getWarehouseOrderById({ ids: keys }).then(async response => {
      if (response.success) {
        datas = response.data
        pick_type = await commonApi.getDict('pick_type')
        buff_type = await commonApi.getDict('butt_type')
        let ss = await predictionAddress.getAddressById({ dept_id: response.data[0].dept_id })
        addresslist = ss.data
        pick_type = pick_type['data']
        buff_type = buff_type['data']
        addobj.delivery_mobile = ''
        addobj.delivery_address = ''
        addobj.delivery_tel = ''
        addobj.delivery_unit = ''
        pick_method.value = ''
        pick_typeid.value = ''
        address_id.value = ''
        buff_typeid.value = ''
        drivers_id.value = ''
        predictionOrderDetail.getDrivers({dept_id:datas[0].dept_id,pageSize:200}).then(res=>{
          drivers.value = res.data.items
          fdslvisible.value = true;
        })
      }

    })
  }

  const addressChange = async (row) => {
  let aa = await predictionAddress.getAddressInfo({ id: row })
  addobj.delivery_mobile = aa.data.mobile
  addobj.delivery_address = aa.data.address
  addobj.delivery_tel = aa.data.tel
  addobj.delivery_unit = aa.data.unit
  addobj.lat = aa.data.lat
  addobj.lng = aa.data.lng

}



</script>
<script>
	export default { name: "warehouse:order" };
</script>

<style lang="less" scoped>
.input {
  width: 100px;
  padding: 4px 12px;
  background: rgba(242, 243, 245);
  border: 1px solid rgba(242, 243, 245);
  border-radius: 4px;
  outline: none;
  /*清除input点击之后的黑色边框*/
}

.input:focus {
  background: #fff;
  border: 1px solid #1e80ff;
}

.arco-upload-wrapper {
  width: 50%;
}
	.view-content {
		height: 75vh;
		width: 794px;
		overflow: hidden;
		display: flex;
		flex-direction: column;
	}

	.form {
		display: flex;
		padding: 24px 36px 0 0;
		flex-wrap: wrap;
		justify-content: space-between;
		align-items: center;
		flex: 0 0 auto;
		> .form-item {
			width: 45%;
			margin-bottom: 24px;
			display: flex;
			flex: 1 0 auto;
			padding-left: 36px;
			align-items: center;
			max-width: 100%;
			box-sizing: border-box;

			lable {
				width: 80px;
				flex-shrink: 0;
			}
		}
	}

	.text-wrap {
		white-space: normal !important;
	}

	.text-left {
		text-align: left !important;
	}

	.border-top {
		border-top: 1px solid #000;
	}

	.border-left {
		border-left: 1px solid #000;
	}

	.border-right {
		border-right: 1px solid #000;
	}

	.border-bottom {
		border-bottom: 1px solid #000;
	}

	.p-2 {
		padding: 2px;
	}

	.p-l {
		padding-left: 10px !important;
	}

	.p-r {
		padding-right: 10px !important;
	}

	.w100 {
		width: 100% !important;
	}
</style>
